package cn.yq.aio.ui;

import android.app.AlertDialog;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothGattCharacteristic;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.provider.Settings;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Toast;

import com.hjq.permissions.OnPermissionCallback;
import com.hjq.permissions.Permission;
import com.hjq.permissions.XXPermissions;
import com.kaer.sdk.IDCardItem;
import com.kaer.sdk.OnClientCallback;
import com.kaer.sdk.bt.BtReadClient;
import com.kaer.sdk.utils.CardCode;
import com.kaer.sdk.utils.LogUtils;

import java.util.List;

import cn.yq.aio.R;
import cn.yq.aio.base.BaseActivity;
import cn.yq.aio.base.MyApp;
import cn.yq.aio.data.MySp;
import cn.yq.aio.databinding.ActivityLoginBinding;
import cn.yq.aio.ui.main.MainActivity;
import cn.yq.aio.utils.BleUtils;
import cn.yq.aio.utils.SystemUtils;
import cn.yq.aio.utils.recycler.TShow;

/**
 * 登录
 */
public class LoginActivity extends BaseActivity implements View.OnClickListener {

    public static void toMe(Context context) {
        Intent it = new Intent(context, LoginActivity.class);
        context.startActivity(it);
    }

    private static final String TAG = "LoginActivity";
    ActivityLoginBinding binding;
    BleUtils bleUtils;
    BtReadClient btReadClient;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        binding = ActivityLoginBinding.inflate(getLayoutInflater());
        setContentView(binding.getRoot());
        initReadClient();
        initView();
    }

    private void initReadClient() {
        String url = "wss://idcard.kaercloud.top";
        String account = "demo";
        String password = "demo";
        password = getMD5(password.getBytes());
        btReadClient = BtReadClient.getInstance();
        btReadClient.setClientCallback(new OnClientCallback() {
            @Override
            public void preExcute(long l) {

            }

            @Override
            public void updateProgress(int i) {

            }

            @Override
            public void onConnectChange(int i) {

            }
        });
        btReadClient.setReadParams(url, account, password);
    }

    private void initView() {
        binding.btnLogin.setOnClickListener(this);
        binding.ivLoginTypePhone.setOnClickListener(this);
        binding.tvLoginTypePhone.setOnClickListener(this);
        binding.ivLoginTypeId.setOnClickListener(this);
        binding.tvLoginTypeId.setOnClickListener(this);
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.btn_login:
                login();
                break;
            case R.id.iv_login_type_phone:
            case R.id.tv_login_type_phone://手机号登录
                break;
            case R.id.iv_login_type_id:
            case R.id.tv_login_type_id://刷身份证登录
                checkStart();
                break;
        }
    }

    private void login() {
        String name = binding.etNameLogin.getText().toString().trim();

        loginSuccess();
    }

    private void loginSuccess() {
        MySp.getInstance().setValue(MySp.USER_TOKEN, "1");
        MainActivity.toMe(this);
        finish();
    }

    private void checkStart() {
        if (!getPackageManager().hasSystemFeature(PackageManager.FEATURE_BLUETOOTH_LE)) {
            TShow.show("该设备不支持蓝牙");
            return;
        }
        if (bleUtils != null) {
            TShow.show("等待本次测量完成再开始监测");
            return;
        }
        XXPermissions.with(this).permission(Permission.ACCESS_COARSE_LOCATION)
                .request(new OnPermissionCallback() {
                    @Override
                    public void onGranted(List<String> permissions, boolean all) {
                        if (!SystemUtils.isGpsEnable()) {
                            AlertDialog.Builder builder =
                                    new AlertDialog.Builder(LoginActivity.this);
                            builder.setCancelable(false);
                            builder.setTitle("提示")
                                    .setIcon(android.R.drawable.ic_menu_info_details)
                                    .setMessage("蓝牙链接需要开启GPS定位")
                                    .setNegativeButton("取消", new DialogInterface.OnClickListener() {

                                        @Override
                                        public void onClick(DialogInterface dialog, int which) {
                                            dialog.dismiss();
                                        }
                                    }).setPositiveButton("开启",
                                    new DialogInterface.OnClickListener() {

                                        @Override
                                        public void onClick(DialogInterface dialog, int which) {
                                            Intent intent =
                                                    new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
                                            startActivity(intent);
                                        }
                                    });
                            builder.show();
                            return;
                        }
                        readyStart();
                    }

                    @Override
                    public void onDenied(List<String> permissions, boolean never) {
                        TShow.show("蓝牙链接需要开启定位权限");
                    }
                });
    }

    private void readyStart() {
        if (bleUtils != null) {
            Toast.makeText(this, "等待结果", Toast.LENGTH_SHORT).show();
            return;
        }
        bleUtils = new BleUtils(this, new BleUtils.ClassicsCallBack() {
            @Override
            public boolean isNeedDevice(String bleDeviceName) {
                return !TextUtils.isEmpty(bleDeviceName) &&
                        (bleDeviceName.contains("KT"));
            }

            @Override
            public boolean needConnect(BluetoothDevice td) {
                startSdk(td);
                return false;
            }

            @Override
            public String getUUid() {
                return "00001101-0000-1000-8000-00805F9B34FB";
            }
        });
        bleUtils.open(false);
    }

    private void startSdk(final BluetoothDevice td) {
        boolean conn = btReadClient.connectBt(td.getAddress());
        if (!conn) {
            Toast.makeText(this, "设备连接失败", Toast.LENGTH_SHORT).show();
            end();
            return;
        }
        new Thread(new Runnable() {
            @Override
            public void run() {
                boolean conn = btReadClient.connectBt(td);
                if (!conn) {
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            Toast.makeText(LoginActivity.this, "设备连接失败", Toast.LENGTH_SHORT).show();
                        }
                    });
                    end();
                    return;
                }
                try {
                    Thread.sleep(5000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                Log.e(TAG, "读卡");
                IDCardItem result = btReadClient.readCert(1);
                readResult(result);
                end();
                btReadClient.disconnectBt();
                btReadClient.disconnectServer();
            }
        }).start();
    }

    private void readResult(IDCardItem result) {
        if (result == null) {
            Log.e(TAG, "读卡结果失败");
            return;
        }
        Log.e(TAG,
                "读卡结果：" + result.retCode + "  :  " +
                        CardCode.errorCodeDescription(result.retCode));
        if (result.retCode == 1) {//成功
            StringBuilder sb = new StringBuilder();
            sb.append("姓名:" + result.partyName + "\n");
            if ("I".equals(result.idCardType)) {
                sb.append("英文名:" + result.englishName);
            }
            sb.append("性别:" + result.gender + "\n");
            if (!"J".equals(result.idCardType)) {
                sb.append("民族:" + result.nation + "\n");
                sb.append("民族编码:" + result.nationCode + "\n");
            }
            sb.append("出生:" + result.bornDay + "\n");
            if (!"I".equals(result.idCardType)) {

                sb.append("住址:" + result.certAddress + "\n");
            }
            sb.append("证件号:" + result.certNumber + "\n");
            sb.append("签发机关:" + result.certOrg + "\n");
            sb.append("有效期限:" + result.effDate
                    + "-" + result.expDate + "\n");
            sb.append("证件类型标识:" + result.idCardType + "\n");
            if ("J".equals(result.idCardType)) {
                sb.append("通行证号码:" + result.passNumber + "\n");
                sb.append("签发次数:" + result.numberOfIssues + "\n");
            }
            Log.e(TAG, "result.fingerprint == null " + (result.fingerprint == null));
            if (result.collectKey != null) {
                sb.append("caiji_key:" + result.collectKey + "\n");
            }
//        if (result.fingerprint != null) {
//            sb.append("指纹特征:" + ByteUtils.byteToHexString(result.fingerprint));
//        }
//        String effDate = result.effDate;
//        String expDate = result.expDate;
//        sb.append("有效期限:" + effDate.substring(0, 4) + "." + effDate.substring(4, 6) + "." +
//        effDate.substring(6, 8)
//                + "-" + expDate.substring(0, 4) + "." + expDate.substring(4, 6) + "." + expDate
//                .substring(6, 8) + "\n");
            if (!TextUtils.isEmpty(result.uuid)) {
                LogUtils.i("uuid " + result.uuid);
                sb.append("唯一标识:" + result.uuid + "\n");
            }
            if (!TextUtils.isEmpty(result.readUUID)) {
                LogUtils.i("readUUID " + result.readUUID);
                sb.append("唯一标识:" + result.readUUID + "\n");
            }

            if (!TextUtils.isEmpty(result.timestamp)) {
                LogUtils.i("timestamp " + result.timestamp);
                sb.append("读证时间戳:" + result.timestamp + "\n");
            }
            if (!TextUtils.isEmpty(result.procId)) {
                LogUtils.i("procId " + result.procId);
                sb.append("读证token流水:" + result.procId + "\n");
            }
            if (!TextUtils.isEmpty(result.contentSign)) {
                LogUtils.i("contentSign " + result.contentSign);
                sb.append("文本签名:" + result.contentSign + "\n");
            }
            if (!TextUtils.isEmpty(result.photoSign)) {
                LogUtils.i("photoSign " + result.photoSign);
                sb.append("照片签名:" + result.photoSign + "\n");
            }
            if (!TextUtils.isEmpty(result.dn))
                sb.append("dn:" + result.dn + "\n");
            if (!TextUtils.isEmpty(result.timeTag))
                sb.append("timeTag:" + result.timeTag + "\n");
            if (!TextUtils.isEmpty(result.nfcSignature))
                sb.append("nfcSignature:" + result.nfcSignature + "\n");
            if (!TextUtils.isEmpty(result.sha1Sign))
                sb.append("sha1Sign:" + result.sha1Sign + "\n");
            Log.e(TAG, sb.toString());
//                        String str = "";
//                        LogUtils.i("str.length " + str.length());
//                        LogUtils.i("idCardType " + result.idCardType + ", length " + result
//                        .idCardType.length());
//
//                        LogUtils.i(sb.toString());
//                        if (result.picBitmap != null) {
//                            photoIv.setImageBitmap(scale(result.picBitmap));
//                            String base64 = bitmapToBase64(result.picBitmap);
////            saveBase64ToFile(base64);
//                            saveBtimapToFile(result.picBitmap);
//                        } else
//                            LogUtils.e("result.picBitmap = null");
        }
    }

    @Override
    public void onResume() {
        super.onResume();
    }

    @Override
    public void onStop() {
        super.onStop();
        end();
    }

    private void end() {
        if (bleUtils != null)
            bleUtils.close();
        bleUtils = null;
        if (btReadClient != null) {
            btReadClient.disconnectServer();
            btReadClient.disconnectBt();
        }
    }

    public String getMD5(byte[] source) {
        String s = null;
        char hexDigits[] = { // 用来将字节转换成 16 进制表示的字符
                '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd',
                'e', 'f'};
        try {
            java.security.MessageDigest md = java.security.MessageDigest
                    .getInstance("MD5");
            md.update(source);
            byte tmp[] = md.digest(); // MD5 的计算结果是一个 128 位的长整数，
            // 用字节表示就是 16 个字节
            char str[] = new char[16 * 2]; // 每个字节用 16 进制表示的话，使用两个字符，
            // 所以表示成 16 进制需要 32 个字符
            int k = 0; // 表示转换结果中对应的字符位置
            for (int i = 0; i < 16; i++) { // 从第一个字节开始，对 MD5 的每一个字节
                // 转换成 16 进制字符的转换
                byte byte0 = tmp[i]; // 取第 i 个字节
                str[k++] = hexDigits[byte0 >>> 4 & 0xf]; // 取字节中高 4 位的数字转换,
                // >>> 为逻辑右移，将符号位一起右移
                str[k++] = hexDigits[byte0 & 0xf]; // 取字节中低 4 位的数字转换
            }
            s = new String(str); // 换后的结果转换为字符串

        } catch (Exception e) {
            e.printStackTrace();
        }
        return s;
    }
}
